package com.baomidou.wechat.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 输入流与字符串处理工具类
 */
public class StreamUtil {

	private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class);

	/**
	 * 输入流转为输出文件
	 * 
	 * @param bufferedIn
	 *            输入流
	 * @param file
	 *            输入文件
	 */
	public static boolean outputFile(BufferedInputStream bufferedIn, File file) {
		try {
			FileOutputStream fo = new FileOutputStream(file);
			BufferedOutputStream bufferedOut = new BufferedOutputStream(fo);
			byte[] data = new byte[1];
			while (bufferedIn.read(data) != -1) {
				bufferedOut.write(data);
			}
			bufferedOut.flush();
			bufferedIn.close();
			bufferedOut.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 将字符串转换成输入流
	 *
	 * @param str
	 *            字符串
	 * @return 输入流
	 */
	public static InputStream toStream(String str) {
		InputStream stream = null;
		try {
			/* UTF-8 解决网络传输中的字符集问题 */
			stream = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error("转换输出Stream异常,不支持的字符集!!! ", e);
		}
		return stream;
	}

	/**
	 * InputStream 转化为字节数组
	 */
	public static byte[] toBytes(InputStream inputStream) {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = inputStream.read(b)) != -1)
				out.write(b, 0, n);
			inputStream.close();
			out.close();
			return out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
